//
//  DLPieChartView.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/12/5.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLPieChartView.h"

@interface DLPieChartView()
@property (nonatomic, strong) NSMutableArray *colors;
@property (nonatomic, strong) UILabel *subTitleLabel;
@property (nonatomic, strong) UILabel *subRightTitle;
@end

@implementation DLPieChartView

- (void) chartValueSelected:(ChartViewBase *)chartView entry:(ChartDataEntry *)entry highlight:(ChartHighlight *)highlight {
    NSLog(@"图表中的数值被选中");
    
    
    NSString *pieIndex = [NSString stringWithFormat:@"%@", entry.data];
    NSDictionary *dic = self.dataSourceDic[@"data"];
    
    NSArray *colLabelArray = [NSArray arrayWithArray:dic[@"ColLabel"]];
    NSString *colString = [NSString stringWithFormat:@"%@", colLabelArray[pieIndex.integerValue]];
    
    NSArray *vDataArray = [NSArray arrayWithArray:dic[@"vData"]];
    
    if (vDataArray.count > 0) {
        
        NSString *vDataString = [NSString stringWithFormat:@"%@", vDataArray[pieIndex.integerValue]];
        self.subRightTitle.hidden = NO;
        NSString *subRightText = [NSString stringWithFormat:@"%@：%@", colString, vDataString];
        self.subRightTitle.text = subRightText;
        
        UIColor *color = self.colors[pieIndex.integerValue - 1];
        
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self.subRightTitle.text];
        [attrStr addAttribute:NSForegroundColorAttributeName
                        value:color
                        range:NSMakeRange(colString.length + 1, vDataString.length)];
        self.subRightTitle.attributedText = attrStr;
    } else {
        
        self.subTitleLabel.hidden = YES;
        self.subRightTitle.hidden = YES;
    }
    
    
    
    
    
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self layoutSubControls];
        
        self.xValuesDataSource = [NSMutableArray array];
        self.backgroundColor = kDLMachineTableAndCellBgColor;
        self.backgroundColor = [UIColor whiteColor];
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(17, 17)];
        
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = maskPath.bounds;
        maskLayer.path = maskPath.CGPath;
        self.layer.mask  = maskLayer;
    }
    return self;
}
- (void) layoutSubControls {
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.frame = CGRectMake(12, 10, self.width - 24, 20);
    titleLabel.textColor = kDLNormalBlackColor;
    titleLabel.font = kBoldFont(14);
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.backgroundColor = [UIColor whiteColor];
    [self addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    UILabel *subTitleLabel = [UILabel new];
    subTitleLabel.frame = CGRectMake(titleLabel.left + 9, titleLabel.bottom, titleLabel.width / 2, titleLabel.height);
    subTitleLabel.textColor = kDLNormalBlackColor;
    subTitleLabel.textAlignment = NSTextAlignmentLeft;
    subTitleLabel.font = kSystemFont(14);
    subTitleLabel.backgroundColor = [UIColor whiteColor];
    [self addSubview:subTitleLabel];
    self.subTitleLabel = subTitleLabel;
    subTitleLabel.hidden = YES;
    
    UILabel *subRightTitle = [UILabel new];
    subRightTitle.frame = CGRectMake(subTitleLabel.right, subTitleLabel.top, subTitleLabel.width, subTitleLabel.height);
    subRightTitle.textColor = kDLNormalBlackColor;
    subRightTitle.textAlignment = NSTextAlignmentLeft;
    subRightTitle.font = kSystemFont(14);
    subRightTitle.backgroundColor = [UIColor whiteColor];
    [self addSubview:subRightTitle];
    self.subRightTitle = subRightTitle;
    subRightTitle.hidden = YES;
    
    
    PieChartView *pieChartView = [[PieChartView alloc] initWithFrame:CGRectMake(kMachineChartsChartLeftMargin, 0, self.width - kMachineChartsChartLeftMargin *2, kMachineChartsHeight - 40)];
    [pieChartView setExtraOffsetsWithLeft:0 top:30 right:0 bottom:10];
    pieChartView.delegate = self;
    [self addSubview:pieChartView];
    self.pieChartView = pieChartView;
    pieChartView.backgroundColor = kDLMachineTableAndCellBgColor;
    pieChartView.backgroundColor = [UIColor whiteColor];
    
//    pieChartView.usePercentValuesEnabled = YES;//是否根据所提供的数据, 将显示数据转换为百分比格式
    pieChartView.dragDecelerationEnabled = YES;//拖拽饼状图后是否有惯性效果
    pieChartView.drawCenterTextEnabled = NO;//是否显示区块文本
    
    pieChartView.drawHoleEnabled = YES;//饼状图是否是空心
    pieChartView.holeRadiusPercent = 0.4;//空心半径占比
    pieChartView.holeColor = [UIColor clearColor];//空心颜色
    pieChartView.transparentCircleRadiusPercent = 0.5;//半透明空心半径占比
    pieChartView.transparentCircleColor = [UIColor clearColor];//半透明空心的颜色
    
//    if (pieChartView.isDrawHoleEnabled == YES) {
//        pieChartView.drawCenterTextEnabled = YES;//是否显示中间文字
        //普通文本
//        self.pieChartView.centerText = @"饼状图";//中间文字
//        富文本
//        NSMutableAttributedString *centerText = [[NSMutableAttributedString alloc] initWithString:@""];
//        [centerText setAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:16],
//                                    NSForegroundColorAttributeName: [UIColor orangeColor]}
//                            range:NSMakeRange(0, centerText.length)];
//        pieChartView.centerAttributedText = centerText;
//    }
    
    pieChartView.legend.enabled = YES;
    pieChartView.legend.maxSizePercent = 1;//图例在饼状图中横向宽度占比, 这会影响图例的宽高，取值0-1
    pieChartView.legend.formToTextSpace = 5;//文本间隔
    pieChartView.legend.font = [UIFont systemFontOfSize:10];//字体大小
    pieChartView.legend.textColor = kDLNormalBlackColor;//字体颜色
    pieChartView.legend.direction = ChartLegendDirectionLeftToRight;
    pieChartView.legend.form = ChartLegendFormSquare;//图示样式: 方形、线条、圆形
    pieChartView.legend.formSize = 10;//图示大小
    
    
    [subTitleLabel resetY:pieChartView.bottom - 50];
    [self bringSubviewToFront:titleLabel];
    [self bringSubviewToFront:subTitleLabel];
    
    [subRightTitle resetY:subTitleLabel.top];
    [self bringSubviewToFront:subRightTitle];
}
- (void) setDataSourceDic:(NSDictionary *)dataSourceDic {
    _dataSourceDic = dataSourceDic;
    
    NSDictionary *dic = dataSourceDic[@"data"];
//    NSLog(@"饼图数据源：%@", dic);
    self.titleLabel.text = [NSString stringWithFormat:@"%@", dic[@"title"]];
    
    NSArray *colLabelArray = [NSArray arrayWithArray:dic[@"ColLabel"]];
    NSString *colString = [NSString stringWithFormat:@"%@", colLabelArray[0]];
    
    NSArray *kDataArray = [NSArray arrayWithArray:dic[@"kData"]];
    
    NSArray *vDataArray = [NSArray arrayWithArray:dic[@"vData"]];
    
    
    if (vDataArray.count) {
        self.subTitleLabel.hidden = NO;
        NSString *totalMoney = [NSString stringWithFormat:@"%@", vDataArray[0]];
        self.subTitleLabel.text = [NSString stringWithFormat:@"%@：%@", colString, totalMoney];
        
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self.subTitleLabel.text];
        [attrStr addAttribute:NSForegroundColorAttributeName
                        value:kColorRGB(255, 90, 62)
                        range:NSMakeRange(colString.length + 1, totalMoney.length)];
        self.subTitleLabel.attributedText = attrStr;
    } else {
        self.subTitleLabel.hidden = YES;
    }
    
    
    
    
    NSMutableArray *yVals = [[NSMutableArray alloc] init];
    
    if (colLabelArray.count && kDataArray.count) {
        
        for (NSInteger i = 1; i < colLabelArray.count; i++) {
            
            NSString *values = [NSString stringWithFormat:@"%@", kDataArray[i]];
            
//            NSString *valuesWithOutPercent = [values substringToIndex:values.length - 1];
            
            NSString *prefixNames = [NSString stringWithFormat:@"%@", colLabelArray[i]];
//            NSString *tailName = [NSString stringWithFormat:@"%@", vDataArray[i]];
            
            if ([values containsString:@"--"]) {
                continue;
            }
            
            PieChartDataEntry *entry = [[PieChartDataEntry alloc] initWithValue:values.doubleValue label:prefixNames data:[NSString stringWithFormat:@"%ld", i]];
            [yVals addObject:entry];
        }
    }
    
    //dataSet
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:yVals label:@""];
    dataSet.drawValuesEnabled = YES;//是否绘制显示数据
    NSMutableArray *colors = [[NSMutableArray alloc] init];

    [colors addObject:kColorRGB(181, 194, 202)];
    [colors addObject:kColorRGB(129, 216, 200)];
    [colors addObject:kColorRGB(241, 214, 145)];
    [colors addObject:kColorRGB(108, 176, 223)];
    [colors addObject:kColorRGB(195, 221, 155)];
    [colors addObject:kColorRGB(251, 215, 191)];
    [colors addObject:kColorRGB(237, 189, 189)];
    [colors addObject:kColorRGB(172, 217, 243)];
    [colors addObject:kColorRGB(255, 151, 3)];
    [colors addObject:kColorRGB(9, 150, 142)];
    [colors addObject:kColorRGB(205, 51, 1)];
    [colors addObject:kColorRGB(153, 52, 0)];
    [colors addObject:kColorRGB(204, 101, 1)];
    self.colors = colors;

    
    dataSet.colors = colors;//区块颜色
    dataSet.sliceSpace = 1;//相邻区块之间的间距
    dataSet.selectionShift = 5;//选中区块时, 放大的半径
    dataSet.xValuePosition = PieChartValuePositionOutsideSlice;//名称位置
    dataSet.yValuePosition = PieChartValuePositionOutsideSlice;//数据位置
    //数据与区块之间的用于指示的折线样式
    dataSet.valueLinePart1OffsetPercentage = 0.7 ;//折线中第一段起始位置相对于区块的偏移量, 数值越大, 折线距离区块越远
    dataSet.valueLinePart1Length = 0.6;//折线中第一段长度占比
    dataSet.valueLinePart2Length = 0.8;//折线中第二段长度最大占比
    dataSet.valueLineWidth = 1;//折线的粗细
    dataSet.valueLineColor = kDLNormalBlackColor;//折线颜色
    
    dataSet.valueTextColor = kDLNormalBlackColor;
    
    dataSet.valueLineVariableLength = NO;
//    dataSet.highlightColor = kDLBtnNormalBgColor;
    
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterPercentStyle;
    formatter.maximumFractionDigits = 2;//小数位数
    formatter.multiplier = @1.f;
    [dataSet setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:formatter]];
    
    //data
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    
    self.pieChartView.data = data;
    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
